package com.solution.wx.order.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.constants.OrderConstants.ORDER_PAY_MODEL;
import com.solution.admin.order.constants.OrderConstants.ORDER_PAY_STATUS;
import com.solution.admin.order.constants.OrderConstants.ORDER_STATUS;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderPayEntity;
import com.solution.admin.order.service.OrderService;
import com.solution.common.config.PublicConfigUtil;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.swiftpass.MD5;
import com.solution.common.swiftpass.SignUtils;
import com.solution.common.swiftpass.SwiftpassConfig;
import com.solution.common.swiftpass.SwiftpassPayVO;
import com.solution.common.swiftpass.XmlUtils;
import com.solution.common.utils.DateUtils;
import com.solution.pc.order.entity.OrderAlipayNotifyLogEntity;
import com.solution.pc.order.entity.OrderWxpayNotifyLogEntity;
import com.solution.pc.order.service.OrderWxpayNotifyLogService;
import com.solution.pc.order.task.OrderPayStatusUpdateTask;
import com.solution.pc.order.task.OrderStatusFixedThreadPool;
import com.solution.wx.order.config.WxpayConfig;

/**
 * 微信支付网关
 * @author xkl
 * @date 2017年11月23日 下午2:56:32
 */
@RequestMapping("/wx/wxpay")
@Controller
public class WxOrderPayController extends BaseController {

	Logger logger = LoggerFactory.getLogger(WxOrderPayController.class);

	@Autowired
	private OrderService orderService;

	@Autowired
	private OrderWxpayNotifyLogService orderWxpayNotifyLogService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CustomerService customerService;

	/**
	 * 微信订单支付(不用,手机端微信支付使用wxOrderController)
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author xkl
	 * @date 2017年11月23日 下午2:57:40
	 */
	@RequestMapping("/payOrder")
	public String wxpayOrder(HttpServletRequest request,HttpServletResponse response) {
		try {
			WxpayConfig config = WxpayConfig.getInstance();
			WXPay wxPay = new WXPay(config);

			// 查询订单信息进行支付
			String orderCode = request.getParameter("orderCode");
			OrderEntity order = orderService.getOrderByCode(orderCode);
			if (null == order || !ORDER_STATUS.WAIT_TO_PAY.getCode().equals(order.getOrderStatus())) {
				request.setAttribute("errMessage", "该订单不是待支付订单");
				return "wx/wx_error";
			}
			CustomerEntity customer = customerService.getCustomerById(getCustomerId());

			//创建订单交易记录
			String currentUserCode = getCurrentUserCodeWithAnonymous(request).toLowerCase();
			String outTradeNo = "wx"+OrderConstants.ORDER_CHANNEL.PC.getCode()
					+String.valueOf(System.currentTimeMillis()).substring(3)
					+currentUserCode.substring(currentUserCode.length()-4);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orderCode", orderCode);
			paramMap.put("outTradeNo", outTradeNo);
			paramMap.put("creater", getUserName());
			int count = orderService.saveOrderTrade(paramMap);
			if (count != 1) {
				request.setAttribute("errMessage", "生成订单交易记录失败");
				return "wx/wx_error";
			}
			
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("body", "景旭商城订单支付");
			data.put("out_trade_no", order.getOrderCode());
			data.put("fee_type", "CNY");
			data.put("total_fee", String.valueOf(order.getRealPayMoney().multiply(new BigDecimal(100)).intValue()));
			data.put("spbill_create_ip", config.getSpbillCreateIp());
			data.put("notify_url", config.getNotifyUrl());
			data.put("trade_type", "JSAPI");
			data.put("product_id", order.getId().toString());
			data.put("openid", customer.getOpenId());
			Map<String, String> prePayMap = wxPay.unifiedOrder(data);
			if (prePayMap.get("return_code").equals("SUCCESS") && prePayMap.get("result_code").equals("SUCCESS")) {
				//组装前端支付参数
				Map<String, String> payMap = new HashMap<String, String>();
				payMap.put("appId", config.getAppID());
				payMap.put("timeStamp", String.valueOf(System.currentTimeMillis()/1000));
				payMap.put("nonceStr", data.get("nonce_str"));
				payMap.put("package", "prepay_id="+prePayMap.get("prepay_id"));
				payMap.put("signType", data.get("sign_type"));
				//签名(package为关键字,前台无法读取,只作为后端签名使用,前端使用prepayId重新组装)
				payMap.put("paySign", WXPayUtil.generateSignature(payMap, config.getKey(), WXPayConstants.SignType.MD5));
				payMap.put("prepayId", prePayMap.get("prepay_id"));
				request.setAttribute("payMap", payMap);
				return "wx/order/wx_pay";
			} else {
				if (prePayMap.get("return_code").equals("SUCCESS")) {
					request.setAttribute("errMessage", prePayMap.get("err_code_des"));
				} else {
					request.setAttribute("errMessage", prePayMap.get("return_msg"));
				}
				return "wx/wx_error";
			}
		} catch (Exception e) {
			handleException("微信支付败", logger, e);
		}
		request.setAttribute("errMessage", "支付失败");
		return "wx/wx_error";
	}

	/**
	 * 微信二维码支付
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月26日 下午6:37:42
	 */
	@RequestMapping("/preWxpayQRCode")
	@ResponseBody
	public Map<String, Object> preWxpayQRCode(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			WxpayConfig config = WxpayConfig.getInstance();
			WXPay wxPay = new WXPay(config);

			// 查询订单信息进行支付
			String orderCode = request.getParameter("orderCode");
			OrderEntity order = orderService.getOrderByCode(orderCode);
			//检查订单
			if (null == order) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "订单不存在");
				return resultMap;
			}
			if (!ORDER_PAY_STATUS.NOT_PAY.getCode().equals(order.getPayStatus())) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "该订单已支付");
				return resultMap;
			}
			
			//创建订单交易记录
			String currentUserCode = getCurrentUserCodeWithAnonymous(request).toLowerCase();
			String outTradeNo = "wx"+OrderConstants.ORDER_CHANNEL.PC.getCode()
					+String.valueOf(System.currentTimeMillis()).substring(3)
					+currentUserCode.substring(currentUserCode.length()-4);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orderCode", orderCode);
			paramMap.put("outTradeNo", outTradeNo);
			paramMap.put("creater", getUserName());
			int count = orderService.saveOrderTrade(paramMap);
			if (count != 1) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "生成交易记录失败");
				return resultMap;
			}
			
			HashMap<String, String> data = new HashMap<String, String>();
			data.put("body", "景旭商城订单支付");
			data.put("out_trade_no", outTradeNo);
			data.put("fee_type", "CNY");
			data.put("total_fee", String.valueOf(order.getRealPayMoney().multiply(new BigDecimal(100)).intValue()));
			data.put("spbill_create_ip", config.getSpbillCreateIp());
			data.put("notify_url", config.getNotifyUrl());
			data.put("trade_type", "NATIVE");
			data.put("product_id", order.getId().toString());
			Map<String, String> prePayMap = wxPay.unifiedOrder(data);
			if (prePayMap.get("return_code").equals("SUCCESS") && prePayMap.get("result_code").equals("SUCCESS")) {
				resultMap.put("QRCode", prePayMap.get("code_url"));
				resultMap.put(PublicStatus.RESULT_CODE, 1);
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			} else {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "生成支付码失败");
			}
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "生成支付码失败");
			handleException("微信扫码支付败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 微信支付异步通知
	 * @param request
	 * @param response
	 * @return
	 * @author xkl
	 * @date 2017年11月23日 下午4:16:06
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("wxpayNotify")
	public void wxpayNotify(HttpServletRequest request, HttpServletResponse response) {
		//给微信的返回结果
		Map<String, String> reqData = new HashMap<String, String>();
		Map<String, String> params = new HashMap<String, String>();
		String reqStr = "";
		
		//微信的通知
		StringBuffer sb = new StringBuffer();
		String s;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			params = WXPayUtil.xmlToMap(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			handleException("微信支付异步通知失败", logger, e);
		}
		
		//获取交易流水对应的订单号
		String orderCode = orderService.getOrderCodeByOutTradeNo(params.get("out_trade_no"));

		// 记录异步通知的日志
		OrderWxpayNotifyLogEntity wxpayLog = new OrderWxpayNotifyLogEntity();
		wxpayLog.setOrderCode(orderCode);
		wxpayLog.setOutTradeNo(params.get("out_trade_no"));
		wxpayLog.setTradeNo(params.get("transaction_id"));
		wxpayLog.setBuyerPayAmount(new BigDecimal(params.get("total_fee")));
		wxpayLog.setReceiptAmount(new BigDecimal(params.get("total_fee")));
		wxpayLog.setNotifyType("01");  // 01 异步 02 同步
		wxpayLog.setNotifyTime(DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
		wxpayLog.setTradeStatus(params.get("result_code"));
		wxpayLog.setNotifyContent(JSONObject.toJSONString(params));
		wxpayLog.setRsaCheckTime(new Date());
		//验证签名
		boolean signVerified = false;
		try {
			WxpayConfig config = WxpayConfig.getInstance();
			signVerified = WXPayUtil.isSignatureValid(params, config.getKey(), WXPayConstants.SignType.MD5);
			if(signVerified){
				wxpayLog.setRsaCheckResult("success");
				// 插入订单支付记录，并修改订单状态为支付成功
				OrderPayEntity orderPay = new OrderPayEntity();
				orderPay.setOrderCode(orderCode);
				orderPay.setPayCode(params.get("transaction_id"));
				orderPay.setPayTime(DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
				orderPay.setPayMoney(new BigDecimal(params.get("total_fee")));
				orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.WXPAY.getCode());
				orderPay.setConfirmStatus(OrderConstants.ORDER_PAY_CONFIRM_STATUS.NOT_CONFIRM.getCode());
				orderPay.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
				orderPay.setCreater("system");
				orderPay.setCreateTime(new Date());
				
				Map<String, Object> payParam = new HashMap<String, Object>();
				payParam.put("orderPay", orderPay);
				payParam.put("orderCode", orderCode);
				
				// 支付成功，修改订单状态(立即付款进入待审核，货到付款进入待核销)
				OrderEntity order = orderService.getOrderByCode(orderCode);
				if (ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())) {
					payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
				} else if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
					payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
				} else {
					//支付方式错误,进入待审核
					payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
				}
				
				//支付成功，订单改为已支付状态
				payParam.put("payStatus", OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
				payParam.put("payTime", DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));

				//记录日志
				OrderLogEntity orderLog = new OrderLogEntity();
				orderLog.setOrderCode(orderCode);
				orderLog.setOperaterCode("");
				orderLog.setOperaterName("微信支付通知");
				orderLog.setOpTime(new Date());
//				orderLog.setLogType(logType);
				orderLog.setLogContent("支付订单成功");
				orderLog.setCreater("微信支付通知");
				payParam.put("orderLogEntity", orderLog);
				
				// 异步执行更新订单状态，不影响支付宝接口返回
				OrderPayStatusUpdateTask opsuTask = new OrderPayStatusUpdateTask(payParam);
				opsuTask.setOrderService(orderService);
				OrderStatusFixedThreadPool.addTask(opsuTask);
				
				//微信返回
				reqData.put("return_code", "SUCCESS");
				reqData.put("return_msg", "OK");
			} else {
				reqData.put("return_code", "FAIL");
				reqData.put("return_msg", "校验失败");
				wxpayLog.setRsaCheckResult("failure");
			}
			reqStr = WXPayUtil.mapToXml(reqData);
		} catch (Exception e) {
			handleException("微信支付异步通知失败", logger, e);
			wxpayLog.setRsaCheckResult("failure");
			wxpayLog.setRsaBizCheckReason(e.getMessage());
		} finally{
			// 记录异步通知日志
			orderWxpayNotifyLogService.saveOrderWxpayNotifyLog(wxpayLog);
		} 
		try {
            // ------------------------------
            // 处理业务完毕
            // ------------------------------
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(reqStr.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
			handleException("微信支付异步通知失败", logger, e);
        }
	}
	
	
	/**
	 * 北京银行微信支付二维码生成
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/swift/payOrder")
	@ResponseBody
	public SwiftpassPayVO swiftXxpayOrder(HttpServletRequest req,HttpServletResponse resp) throws Exception{
		SwiftpassPayVO swiftpassPayVO = new SwiftpassPayVO();
		req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        SortedMap<String,String> map = new TreeMap<String, String>();
        
	    // 查询订单信息进行支付
	    String orderCode = req.getParameter("orderCode");
	    OrderEntity order = orderService.getOrderByCode(orderCode);
	    if (null == order || !ORDER_STATUS.WAIT_TO_PAY.getCode().equals(order.getOrderStatus())) {
	    	// 订单支付状态不对
	    	swiftpassPayVO.setPrePayStatus("1");
	    	swiftpassPayVO.setErrorMessage("支付状态错误，无法进行支付");
	        return swiftpassPayVO;
	    }
	    //创建订单交易记录,生成新的临时订单号，用于调价支付
	    String currentUserCode = getUserCode();
	    String outTradeNo = "wx"+OrderConstants.ORDER_CHANNEL.PC.getCode()
	  			+String.valueOf(System.currentTimeMillis()).substring(3)
	  			+currentUserCode.substring(currentUserCode.length()-4);
	    Map<String, Object> paramMap = new HashMap<String, Object>();
	    paramMap.put("orderCode", order.getOrderCode());
	    paramMap.put("outTradeNo", outTradeNo);
	    paramMap.put("creater", getUserName());
	    try {
	    	// 订单中关键了自定义支付订单号，为了应对订单调价后无法支付的情况 
	    	orderService.saveOrderTrade(paramMap);
	    } catch (Exception e) {
	    	logger.error(e.getMessage());
	    	swiftpassPayVO.setPrePayStatus("1");
	    	swiftpassPayVO.setErrorMessage("预支付生成二维码失败");
	        return swiftpassPayVO;
	    }
        
        map.put("service", "pay.weixin.native");
		// 商品订单号
		map.put("out_trade_no", outTradeNo);
		// 商户号
		map.put("body", "景旭分销商城订单");
		// 支付客户端IP
		map.put("mch_create_ip", SwiftpassConfig.getMchCreateIp());
		// 商户号
		map.put("mch_id", SwiftpassConfig.getMchId());
		// 支付金额，单位为分
		map.put("total_fee", String.valueOf((order.getRealPayMoney().multiply(new BigDecimal(100))).intValue()));
		// 异步通知地址
	    map.put("notify_url", SwiftpassConfig.getWxPayNotifyUrl());
	    // 支付随机数
	    map.put("nonce_str", String.valueOf(new Date().getTime()));
	    // 操作员编号，这是我们放入原始订单号，方便在银行的商户后台对账查询
	    map.put("op_user_id", orderCode);
		// 签收 
		Map<String, String> params = SignUtils.paraFilter(map);
		StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
		SignUtils.buildPayParams(buf, params, false);
		String preStr = buf.toString();
		String sign = MD5.sign(preStr,"&key=" + SwiftpassConfig.getKey(),"utf-8");
		map.put("sign", sign);

		String reqUrl = SwiftpassConfig.getPayReqUrl();
		System.out.println("reqUrl：" + reqUrl);
		System.out.println("reqParams:" + XmlUtils.parseXML(map));
		CloseableHttpResponse response = null;
		CloseableHttpClient client = null;
		String res = null;
		try {
			HttpPost httpPost = new HttpPost(reqUrl);
			StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map), "utf-8");
			httpPost.setEntity(entityParams);
			client = HttpClients.createDefault();
			response = client.execute(httpPost);
			if (response != null && response.getEntity() != null) {
				Map<String, String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
				res = XmlUtils.toXml(resultMap);
				System.out.println("请求结果：" + res);
				if("Order paid".equals(resultMap.get("err_code"))){
	            	swiftpassPayVO.setPrePayStatus("1");
                    swiftpassPayVO.setErrorMessage("订单已支付，请勿重复支付!");
	            	return swiftpassPayVO;
	            }
				if (resultMap.containsKey("sign")) {
					if (!SignUtils.checkParam(resultMap,SwiftpassConfig.getKey())) {
						swiftpassPayVO.setPrePayStatus("1");
	                    swiftpassPayVO.setErrorMessage("验证签名不通过");
					} else {
						if ("0".equals(resultMap.get("status"))&& "0".equals(resultMap.get("result_code"))) {
							String codeImgUrl = resultMap.get("code_img_url");
							swiftpassPayVO.setCodeImgUrl(codeImgUrl);
	                        swiftpassPayVO.setOutTradeNo(order.getOrderCode());
	                        swiftpassPayVO.setTotalFee(order.getRealPayMoney());
	                        swiftpassPayVO.setPrePayStatus("0");
		                    swiftpassPayVO.setErrorMessage("生成支付二维码成功");
						} else {
							swiftpassPayVO.setPrePayStatus("1");
		                    swiftpassPayVO.setErrorMessage(resultMap.get("message"));
						}
					}
				}
			} else {
				swiftpassPayVO.setPrePayStatus("1");
                swiftpassPayVO.setErrorMessage("预支付生成二维码失败");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
	    	swiftpassPayVO.setPrePayStatus("1");
            swiftpassPayVO.setErrorMessage("预支付生成二维码失败");
		} finally {
			if (response != null) {
				response.close();
			}
			if (client != null) {
				client.close();
			}
		}
		return swiftpassPayVO;
	}
	
	
	/**
	 * 北京银行微信扫码支付异步通知
	 * @param req
	 * @param resp
	 */
	@RequestMapping("/swift/wxpayNotify")
	public void swiftWxpayNotify(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            String resString = XmlUtils.parseRequst(req);
            String respString = "fail";
            if(resString != null && !"".equals(resString)){
                Map<String,String> map = XmlUtils.toMap(resString.getBytes(), "utf-8");
                String res = XmlUtils.toXml(map);
                System.out.println("通知内容：" + res);
                if(map.containsKey("sign")){
                    if(!SignUtils.checkParam(map, SwiftpassConfig.getKey())){
                        respString = "fail";
                    }else{
                    	// 支付成功
                    	handSwiftWxPaySuccess(map);
                        respString = "success";
                    }
                }
            }
            resp.getWriter().write(respString);
            resp.getWriter().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	try {
				resp.getWriter().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }
	
	
	/**
	 * 支付结果处理逻辑
	 * @param params
	 */
	private boolean handSwiftWxPaySuccess(Map<String, String> params ){
		boolean flag = false;
		// 获取接口返回状态
		String status = params.get("status");
		// 业务结果
		String resultCode = params.get("result_code");
		// 获取交易流水对应的订单号
		String orderCode = orderService.getOrderCodeByOutTradeNo(params.get("out_trade_no"));
		// 判断订单状态，如果为已支付的话， 直接返回成功; 防止产生两条相同的支付流水
		OrderEntity order = orderService.getOrderByCode(orderCode);
		// 记录异步通知的日志
		OrderWxpayNotifyLogEntity wxpayLog = new OrderWxpayNotifyLogEntity();
		// 订单号
		wxpayLog.setOrderCode(orderCode);
		// 支付平台的交易流水号(北京银行的交易流水号)
		wxpayLog.setOutTradeNo(params.get("transaction_id"));
		wxpayLog.setTradeNo(params.get("transaction_id"));
		// 付款金额
		wxpayLog.setBuyerPayAmount(new BigDecimal(params.get("total_fee")));
		// 收款金额
		wxpayLog.setReceiptAmount(new BigDecimal(params.get("total_fee")));
		// 异步
		wxpayLog.setNotifyType("01");
		// 通知时间
		wxpayLog.setNotifyTime(DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
		// 交易状态 0 -成功,非0 -失败
		wxpayLog.setTradeStatus(params.get("status"));
		wxpayLog.setNotifyContent(JSONObject.toJSONString(params));
		wxpayLog.setRsaCheckTime(new Date());
		wxpayLog.setRsaCheckResult(params.get("status"));
		
		
		// 插入订单支付记录，并修改订单状态为支付成功
		OrderPayEntity orderPay = new OrderPayEntity();
		orderPay.setOrderCode(orderCode);
		orderPay.setPayCode(params.get("transaction_id"));
		orderPay.setPayTime(DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
		// 金额还原成以元为单位 
		orderPay.setPayMoney(new BigDecimal(params.get("total_fee")).divide(new BigDecimal(100)));
		orderPay.setPayType(OrderConstants.ORDER_PAY_TYPE.WXPAY.getCode());
		orderPay.setConfirmStatus(OrderConstants.ORDER_PAY_CONFIRM_STATUS.NOT_CONFIRM.getCode());
		orderPay.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
		orderPay.setCreater("system");
		orderPay.setCreateTime(new Date());
		
		try {
			// 接口状态返回成功
			if(status != null && "0".equals(status)){
				if(resultCode != null && "0".equals(resultCode)){
					Map<String, Object> payParam = new HashMap<String, Object>();
					payParam.put("orderPay", orderPay);
					payParam.put("orderCode", orderCode);
					
					// 支付成功，修改订单状态(立即付款进入待审核，货到付款进入待核销)
					if (ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())) {
						payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
					} else if (ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())) {
						payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
					} else {
						//支付方式错误,进入待审核
						payParam.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
					}
					
					//支付成功，订单改为已支付状态
					payParam.put("payStatus", OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
					payParam.put("payTime", DateUtils.getStringDateTime(params.get("time_end"), "yyyyMMddHHmmss"));
					

					//记录日志(插入一条支付成功的订单日志流水记录)
					OrderLogEntity orderLog = new OrderLogEntity();
					orderLog.setOrderCode(orderCode);
					orderLog.setOperaterCode("");
					orderLog.setOperaterName("微信支付通知");
					orderLog.setOpTime(new Date());
					orderLog.setLogContent("支付订单成功");
					orderLog.setCreater("微信支付通知");
					payParam.put("orderLogEntity", orderLog);
					
					// 异步执行更新订单状态，不影响支付宝接口返回
					OrderPayStatusUpdateTask opsuTask = new OrderPayStatusUpdateTask(payParam);
					opsuTask.setOrderService(orderService);
					OrderStatusFixedThreadPool.addTask(opsuTask);
				}else{
					// 接口状态返回支付失败
					wxpayLog.setRsaCheckResult("failure");
				}
			}else{
				// 接口状态返回支付失败
				wxpayLog.setRsaCheckResult("failure");
			}
		} catch (Exception e) {
			flag = false;
		}finally {
			// 记录异步通知日志
			orderWxpayNotifyLogService.saveOrderWxpayNotifyLog(wxpayLog);
		}
		return flag;
	}
	
	
	
}
